package com.xl.web.controller.zoom;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jodd.util.StringUtil;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xl.base.page.PageBean;
import com.xl.base.web.BaseController;
import com.xl.core.constant.Globals;
import com.xl.core.util.DateUtils;
import com.xl.core.util.Encodes;
import com.xl.core.util.HtmlUtil;
import com.xl.core.util.zoom.ZoomRestAPI;
import com.xl.core.util.zoom.model.CreateMeeting;
import com.xl.core.util.zoom.model.ZoomDelete;
import com.xl.core.util.zoom.model.ZoomUpdate;
import com.xl.web.entity.zoom.Company;
import com.xl.web.entity.zoom.Meeting;
import com.xl.web.entity.zoom.SysUser;
import com.xl.web.entity.zoom.ZoomAccount;
import com.xl.web.service.zoom.AccountService;
import com.xl.web.service.zoom.CommonService;
import com.xl.web.service.zoom.MeetingService;
import com.xl.web.service.zoom.UserService;

@Controller
@RequestMapping("/meeting")
public class MeetingController extends BaseController {
	protected static Logger logger = Logger.getLogger(MeetingController.class);
	@Autowired(required = false)
	private MeetingService<Map> meetingService;
	@Autowired(required = false)
	private UserService<SysUser> userService;
	@Autowired(required = false)
	private CommonService<Object> commonService;

	@Autowired(required = false)
	private AccountService<ZoomAccount> accountService;

	/**
	 * 安排会议
	 * 
	 * @param param
	 * @throws Exception
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public void meetingCreate(@RequestBody String param) throws Exception {
		JSONObject paraMap = JSONObject.parseObject(param);
		JSONArray invitationList = new JSONArray();

		CreateMeeting zoomMeeting = new CreateMeeting();
		// 判断必传参数是否为空
		if (!paraMap.containsKey("invitationList")) {
			invitationList = JSONArray.parseArray(paraMap
					.getString("invitationList"));
		}
		// 判断必传参数是否为空
		if (!paraMap.containsKey("createUserId")
				|| StringUtil.isEmpty(paraMap.get("createUserId").toString())) {
			this.sendFailureMessage(response, "创建用户ID不能为空！");
			return;
		}
		if (!paraMap.containsKey("type")
				|| StringUtil.isEmpty(paraMap.get("type").toString())) {
			this.sendFailureMessage(response, "会议类型不能为空！");
			return;
		}

		if (!paraMap.containsKey("hasPassword")
				|| StringUtil.isEmpty(paraMap.get("hasPassword").toString())) {
			this.sendFailureMessage(response, "是否设置密码标识不能为空！");
			return;
		}

		// 判断必传参数是否为空
		if ("1".equals(paraMap.get("hasPassword").toString())) {
			if (!paraMap.containsKey("password")
					|| StringUtil.isEmpty(paraMap.get("password").toString())) {
				this.sendFailureMessage(response, "密码不能为空！！");
				return;
			}
		}
		String password = "";
		if (paraMap.containsKey("password")) {
			password = paraMap.get("password").toString();
		}

		 int repeatType= 1;
		  if (!paraMap.containsKey("repeatType") ||
		   StringUtil.isEmpty(paraMap.get("repeatType").toString())) {
			  repeatType = paraMap.getIntValue("repeatType");
          }
		 
		if (!paraMap.containsKey("topic")
				|| StringUtil.isEmpty(paraMap.get("topic").toString())) {
			this.sendFailureMessage(response, "会议主题不能为空！");
			return;
		}
		int type = paraMap.getInteger("type");
		String startTime = DateUtils.time_sdf.format(new Date());

		int duration = paraMap.getInteger("duration") == null ? 0 : paraMap
				.getInteger("duration");
		if (type > 1) {// 非即时会议
			if (!paraMap.containsKey("startTime")
					|| StringUtil.isEmpty(paraMap.get("startTime").toString())) {
				this.sendFailureMessage(response, "会议开始时间不能为空！");
				return;
			}
			if (!paraMap.containsKey("duration")
					|| StringUtil.isEmpty(paraMap.get("duration").toString())) {
				this.sendFailureMessage(response, "会议时长不能为空！");
				return;
			}
			startTime = paraMap.getString("startTime");
			duration = paraMap.getInteger("duration");
		}
		// 北京时间
		String endTime = DateUtils.getEndTime(startTime, duration);
		paraMap.put("endTime", endTime);
		startTime = DateUtils.getUTCDateTime(startTime);
		// 根据起始时间和开会时长获取会议结束时间
		// 根据userId获取账号信息
		String userId = paraMap.get("createUserId").toString();
		SysUser user = new SysUser(userId);
		List<SysUser> userList = userService.queryUserInfo(user);
		if (userList != null && userList.size() > 0) {
			user = userList.get(0);
		} else {
			this.sendFailureMessage(response, "传入用户错误，当前用户不存在或不可用，请联系管理员!");
			return;
		}
		// 根据传入公司ID和开会人数，从账号池中匹配一个zoom账号
		paraMap.put("type", type);
		ZoomRestAPI.company = user.getCompany();
		zoomMeeting = ZoomRestAPI.createMeeting(user.getHostId(),
				paraMap.getString("topic"), password,
				DateUtils.getUTCDateTime(paraMap.getString("startTime")),
				duration, paraMap.getBoolean("option_jbh"),
				paraMap.getBoolean("option_use_pmi"));

		if (zoomMeeting.getError().getCode() != null) {
			logger.debug(zoomMeeting.getError().getMessage());
			this.sendFailureMessage(response, "创建会议失败，请稍后再试！");
			return;
		}
		Meeting meeting = new Meeting();
		// 创建成功后插入表中
		Map<String, Object> meetingResult = new HashMap<String, Object>();
		try {
			zoomMeeting.setRepeatType(repeatType);
			meeting = meetingService.saveMeeting(user, zoomMeeting);
			if (invitationList != null && invitationList.size() > 0) {
				meetingService
						.saveInvitation(user, zoomMeeting, invitationList);
			}
		} catch (Exception e) {
			// 入库异常时需要回滚会议
			ZoomRestAPI.deleteMeeting(zoomMeeting.getId(), user.getHostId());
			this.sendFailureMessage(response, "创建会议失败!" + e.getMessage());
			return;
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(this.SUCCESS, true);
		result.put(this.MSG, "会议创建成功!");
		result.put("data", meeting);
		HtmlUtil.writerJson(response, result);
	}

	/**
	 * 即时会议
	 * 
	 * @param param
	 * @throws Exception
	 */
	@RequestMapping(value = "/instant", method = RequestMethod.POST)
	public void immediateMeeting(@RequestBody String param) throws Exception {
		JSONObject paraMap = JSONObject.parseObject(param);
		CreateMeeting zoomMeeting = new CreateMeeting();
		// 判断必传参数是否为空
		if (!paraMap.containsKey("createUserId")
				|| StringUtil.isEmpty(paraMap.get("createUserId").toString())) {
			this.sendFailureMessage(response, "创建用户ID不能为空！");
			return;
		}
		if (!paraMap.containsKey("topic")
				|| StringUtil.isEmpty(paraMap.get("topic").toString())) {
			this.sendFailureMessage(response, "会议主题不能为空！");
			return;
		}
		int type = paraMap.getIntValue("type");
		String startTime = DateUtils.datetimeFormat.format(new Date());
		startTime = DateUtils.getUTCDateTime(startTime);
		int duration = 0;
		// 根据userId获取账号信息
		String userId = paraMap.get("createUserId").toString();
		SysUser user = new SysUser(userId);
		List<SysUser> userList = userService.queryUserInfo(user);
		if (userList != null && userList.size() > 0) {
			user = userList.get(0);
		} else {
			this.sendFailureMessage(response, "传入用户错误，当前用户不存在或不可用，请联系管理员!");
			return;
		}
		if (StringUtil.isEmpty(user.getHostId())
				|| StringUtil.isEmpty(user.getToken())) {
			this.sendFailureMessage(response, "当前用户不备具创建会议权限，确认是否已开通？");
		}

		String hasPassword = "";
		if (!paraMap.containsKey("hasPassword")) {
			hasPassword = paraMap.getString("hasPassword");
		}
		String password = "";
		if (!paraMap.containsKey("password")) {
			password = paraMap.getString("password");
		}
		ZoomRestAPI.company = user.getCompany();
		zoomMeeting = ZoomRestAPI.createInstantMeeting(user.getHostId(),
				paraMap.get("topic").toString(), hasPassword, password);
		if (zoomMeeting.getError().getCode() != null) {
			logger.debug(zoomMeeting.getError().getMessage());
			this.sendFailureMessage(response, "创建会议失败:"
					+ zoomMeeting.getError().getMessage());
			return;
		}
		Meeting meeting = new Meeting();
		// 创建成功后插入表中
		Map<String, Object> meetingResult = new HashMap<String, Object>();
		try {
			zoomMeeting.setRepeatType(0);
		    meeting = meetingService.saveMeeting(user, zoomMeeting);
		} catch (Exception e) {
			// 入库异常时需要回滚会议
			ZoomRestAPI.deleteMeeting(zoomMeeting.getId(), user.getHostId());
			this.sendFailureMessage(response, "创建会议失败!" + e.getMessage());
			return;
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(this.SUCCESS, true);
		result.put(this.MSG, "会议创建成功!");
		result.put("data", meeting);
		HtmlUtil.writerJson(response, result);
	}

	/**
	 * 会议查询
	 * 
	 * @param meeting
	 * @param page
	 */
	//包含几部份 1.当前创建人创建未开始的会议 2.邀请人被邀请的会议
	@RequestMapping(value = "/query", method = RequestMethod.GET)
	public void queryMyMeeting() {
		Map paraMap = getRootMap(request);
		Map<String, Object> result = new HashMap<String, Object>();
		PageBean pageBean = meetingService.queryMyMeeting(paraMap);
		result.put(this.SUCCESS, true);
		result.put(this.MSG, "查询成功!");
		result.put("data", pageBean);
		HtmlUtil.writerJson(response, result);
	}

	/**
	 * 开始校验
	 * 
	 * @param meeting
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/check", method = RequestMethod.POST)
	public void meetingAction(@RequestBody String param) {
		JSONObject paraJson = JSONObject.parseObject(param);
		String meetingId = "";
		String meetingNumber = "";
		if (!paraJson.containsKey("status")
				|| StringUtil.isEmpty(paraJson.getString("status"))) {
			this.sendFailureMessage(response, "状态不能空!");
			return;
		}

		if (paraJson.containsKey("meetingId")
				&& !StringUtil.isEmpty(paraJson.getString("meetingId"))) {
			meetingId = paraJson.getString("meetingId");
		}
		if (paraJson.containsKey("meetingNumber")
				&& !StringUtil.isEmpty(paraJson.getString("meetingNumber"))) {
			meetingNumber = paraJson.getString("meetingNumber");
		}

		if (StringUtil.isEmpty(meetingNumber) && StringUtil.isEmpty(meetingId)) {
			this.sendFailureMessage(response, "会议ID和会议号码不能全为空，至少要传一个！");
		}
		String status = paraJson.getString("status").toUpperCase();
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("meetingId", meetingId);
		paraMap.put("meetingNumber", meetingNumber);
		if (status.equals(Globals.MEETINGACTIONTYPEJOIN)) {
			paraMap.put("state", "1");
		} else if (status.equals(Globals.MEETINGACTIONTYPELEAVE)) {
			paraMap.put("state", "1,2");
		} else if (status.equals(Globals.MEETINGACTIONTYPESTARTED)) {
			paraMap.put("state", "0,1");
		} else if (status.equals(Globals.MEETINGACTIONTYPEENDED)) {
			paraMap.put("state", "1,2");
		}
		Meeting meeting = meetingService.queryMeetings(paraMap);
		if (StringUtil.isEmpty(meeting.getId())) {
			this.sendFailureMessage(response, "当前会议不存在或会议未开始或已结束！");
			return;
		}
		// 开始会议前先校验并发数是否已满
		// 根据meetingId查询当前公司是否已达最大连接数
		if (status.equals(Globals.MEETINGACTIONTYPESTARTED)
				|| status.equals(Globals.MEETINGACTIONTYPEJOIN)) {
			boolean limit = meetingService.checkTcpLimit(meeting);
			// 验证不通过！！！
			if (!limit) {
				this.sendFailureMessage(response,
						"公司当前开会人数已达上限，请稍后再试，或与管理员联系增加开会并发数！");
				return;
			}
		}
		// 未受限
		meetingService.meetingAction(meeting, status);
		if (status.equals(Globals.MEETINGACTIONTYPEENDED)) {
			SysUser sysUser = new SysUser(meeting.getCreate_user_id());
			try {
				List<SysUser> userList = userService.queryUserInfo(sysUser);
				sysUser = userList.get(0);
			} catch (Exception e) {
				e.printStackTrace();
			}
			ZoomRestAPI.company = sysUser.getCompany();
			ZoomRestAPI.endMeeting(meeting.getMeeting_number(),
					sysUser.getHostId());
		}
		this.sendSuccessMessage(response, "操作成功！");

	}

	/**
	 * 邀请人接口
	 * 
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addInvitation", method = RequestMethod.POST)
	public void meetingInvitation(@RequestBody String param) {
		// 获取数据
		JSONArray invitationList = JSONArray.parseArray(param);
		if (invitationList.size() == 0) {
			this.sendFailureMessage(response, "邀请人列表为空！");
		}
		meetingService.saveInvitation(invitationList);
		this.sendSuccessMessage(response,
				"添加邀请人成功，本次添加邀请人数为:" + invitationList.size());

	}

	// 更新邀请人信息 方法暂未实现
	/**
	 * 更新邀请人信息
	 * 
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateInvitation")
	public void meetingInvitationUpdate(@RequestBody String param) {
		// 获取数据
		JSONArray invitationList = JSONArray.parseArray(param);
		if (invitationList.size() == 0) {
			this.sendFailureMessage(response, "邀请人列表为空！");
		}
		// 1.判断当前邀请人是否比之前邀请人多，

		meetingService.saveInvitation(invitationList);
		this.sendSuccessMessage(response,
				"添加邀请人成功，本次添加邀请人数为:" + invitationList.size());

	}

	@RequestMapping(value = "/notification", method = RequestMethod.POST)
	public void onMeetingNotification(
			@RequestParam(value = "id", required = false) String meetingId,
			@RequestParam(value = "uuid", required = false) String uuid,
			@RequestParam(value = "status", required = false) String status,
			@RequestParam(value = "host_id", required = false) String hostId,
			@RequestParam(value = "type", required = false) String type,
			@RequestParam(value = "content", required = false) String jsonContent) {
		System.out.println(Encodes.urlDecode(uuid));
		uuid = uuid.replaceAll(" ", "+");
		Map<String, String> paraMap = new HashMap<String, String>();
		paraMap.put("meetingId", uuid);
		Meeting meeting = new Meeting();
		PageBean pageBean = meetingService.queryMyMeeting(paraMap);
		meeting = (Meeting) pageBean.getList().get(0);
		meetingService.meetingAction(meeting, status);
		if (status.equals(Globals.MEETINGACTIONTYPEENDED)) {
			Company company = meetingService.queryCompanyByMeeting(meeting);
			ZoomRestAPI.company = company;
			ZoomRestAPI.endMeeting(meeting.getMeeting_number(), hostId);
		}
		System.out.println("MeetingNotification：当前会议ID为=" + uuid + ",通知类型为="
				+ status);

	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public void deleteMeeting(String meetingId) {
		Map<String, String> paraMap = new HashMap<String, String>();
		paraMap.put("meetingId", meetingId);
		Meeting meeting = meetingService.queryMeetings(paraMap);
		if (meeting != null) {
			// 只有未开始的会议才可以编辑
			if (meeting.getState() > Globals.MEETINGSTATENOSTART) {
				this.sendFailureMessage(response, "只有未开始的会议才可以更新,当前会议已开始或已结束！");
				return;
			}
		} else {
			this.sendFailureMessage(response, "当前会议不存在，请确认！");
			return;
		}
		
		SysUser sysUser = new SysUser(meeting.getCreate_user_id());
		try {
			List<SysUser> userList = userService.queryUserInfo(sysUser);
			sysUser = userList.get(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		ZoomRestAPI.company = sysUser.getCompany();
		ZoomDelete zoomDelete = ZoomRestAPI.deleteMeeting(
				meeting.getMeeting_number(), sysUser.getHostId());
		if (zoomDelete.getError().getCode() != null) {
			this.sendFailureMessage(response, "删除会议失败："
					+ zoomDelete.getError().getMessage());
			return;
		} else {
			meetingService.deleteMeeting(meeting);
		}
		this.sendSuccessMessage(response, "删除会议成功");

	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public void editMeeting(@RequestBody String param) {
		JSONObject meetingJson = JSONObject.parseObject(param);
		String meetingId = "";
		/*
		 * String topic = ""; String startTime = ""; String hasPassword = "";
		 * String password = ""; String duration = ""; boolean option_use_pmi
		 * =false; boolean option_jbh = false;
		 */
		if (meetingJson.containsKey("meetingId")
				&& !"".equals(meetingJson.getString("meetingId"))) {
			meetingId = meetingJson.getString("meetingId");
		} else {
			this.sendFailureMessage(response, "会议ID不能为空！");
			return;
		}

		Map<String, String> paraMap = new HashMap<String, String>();
		paraMap.put("meetingId", meetingId);
		Meeting meeting = meetingService.queryMeetings(paraMap);
		if (meeting != null) {
			// 只有未开始的会议才可以编辑
			if (meeting.getState() > Globals.MEETINGSTATENOSTART) {
				this.sendFailureMessage(response, "只有未开始的会议才可以更新,当前会议已开始或已结束！");
				return;
			}
		} else {
			this.sendFailureMessage(response, "当前会议不存在，请确认！");
			return;
		}
		if (meetingJson.containsKey("topic")
				&& !"".equals(meetingJson.getString("topic"))) {
			meeting.setTopic(meetingJson.getString("topic"));
		}

		if (meetingJson.containsKey("startTime")
				&& !"".equals(meetingJson.getString("startTime"))) {
			meeting.setStart_time(DateUtils.getUTCDateTime(meetingJson
					.getString("startTime")));
		}

		if (meetingJson.containsKey("password")
				&& !"".equals(meetingJson.getString("password"))) {
			meeting.setPassword(meetingJson.getString("password"));
		}
		if (meetingJson.containsKey("duration")
				&& !"".equals(meetingJson.getString("duration"))) {
			meeting.setDuration_hour(meetingJson.getInteger("duration") / 60);
			meeting.setDuration_min(meetingJson.getInteger("duration") % 60);
		}
		if (meetingJson.containsKey("option_use_pmi")
				&& !"".equals(meetingJson.getString("option_use_pmi"))) {
			meeting.setUser_pmi(meetingJson.getBoolean("option_use_pmi"));
		}
		if (meetingJson.containsKey("option_jbh")
				&& !"".equals(meetingJson.getString("option_jbh"))) {
			meeting.setJbh(meetingJson.getBoolean("option_jbh"));
		}
		if (meetingJson.containsKey("modifyUserId")
				&& !"".equals(meetingJson.getString("modifyUserId"))) {
			meeting.setModify_user_id(meetingJson.getString("modifyUserId"));
		}
		if (meetingJson.containsKey("repeatType")
				&& !"".equals(meetingJson.getString("repeatType"))) {
			meeting.setRepeatType(meetingJson.getIntValue("repeatType"));
		}

		SysUser sysUser = new SysUser(meeting.getCreate_user_id());
		try {
			List<SysUser> userList = userService.queryUserInfo(sysUser);
			sysUser = userList.get(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		ZoomRestAPI.company = sysUser.getCompany();
		ZoomUpdate zoomUpdate = ZoomRestAPI.updateMeeting(sysUser.getHostId(),
				meeting.getMeeting_number(), meeting.getTopic(),
				meeting.getPassword(), meeting.getStart_time(),
				meeting.getDuration_hour() * 60 + meeting.getDuration_min(),
				meeting.getJbh(), meeting.getUser_pmi());
		if (zoomUpdate.getError().getCode() != null) {
			this.sendFailureMessage(response, "会议更新失败！"
					+ zoomUpdate.getError().getMessage());
			return;
		} 
		meetingService.updateMeeting(meeting);
		this.sendSuccessMessage(response, "更新会议成功！");
	}
}
